package com.lkd.job;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.wxpay.plus.WxPayParam;
import com.github.wxpay.plus.WxPayTemplate;
import com.lkd.common.VMSystem;
import com.lkd.entity.OrderEntity;
import com.lkd.service.OrderService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-12-06 11:20
 */
@Component
@Slf4j
public class OrderCancelJob {

    @Autowired
    private OrderService orderService;
    @Autowired
    private WxPayTemplate wxPayTemplate;

    @XxlJob("cancelOrder")
    public void cancelOrder(){

        //1.扫描出已经到期并且未支付订单
        List<OrderEntity> list = orderService.list(Wrappers.<OrderEntity>lambdaQuery()
                .eq(OrderEntity::getStatus, VMSystem.ORDER_STATUS_CREATE)
                .le(OrderEntity::getCreateTime, LocalDateTime.now().minusMinutes(15))
        );

        if(CollectionUtils.isNotEmpty(list)){
            for (OrderEntity order : list) {
                //2.修改状态
                order.setStatus(VMSystem.ORDER_STATUS_INVALID);

                //3.调用微信支付接口，让二维码失效
                WxPayParam wxPayParam = new WxPayParam();
                wxPayParam.setOutTradeNo(order.getOrderNo());
                try {
                    wxPayTemplate.closeOrder(wxPayParam);
                } catch (Exception e) {
                    log.error("关闭订单失败,订单号为：" +order.getOrderNo(),e);
                }
            }

            //批量添加
            orderService.updateBatchById(list);
        }

    }
}
